<template>
	<div>
		<div class="toolbar mt-2">
			<a-form ref="searchRef" layout="inline" :model="searchState" @finish="current=1;expandedRowKeys=[];loading=true;initData()">
				<a-form-item label="名称">
					<a-input v-model:value="searchState.name" placeholder="请输入" allow-clear></a-input>
				</a-form-item>

				<a-form-item>
					<a-space>
						<a-button type="primary" html-type="submit">
							<search-outlined />搜索
						</a-button>
					</a-space>
				</a-form-item>
			</a-form>
		</div>

		<div class="container">
			<a-table :columns="columns" :scroll="tableScroll" :expanded-row-keys="expandedRowKeys" row-key="id" :data-source="flowSource" :pagination="pagination" :loading="loading" :row-selection="rowSelection" @change="initData" @expanded-rows-change="expandedRowsChange ">
				<template #bodyCell="{ column, record }">
					<template v-if="column.key === 'flowTypeNodes'">
						<!-- <a-space> -->
						<a-tag v-for="(item) in record.flowTypeNodes" :key="item.id">
							<template #icon>{{ item.no }}</template>
							{{ item.name }}
						</a-tag>

						<!-- </a-space> -->
					</template>
					<template v-else-if="column.key === 'status-1'">
						<a-tag color="pink" @click="clickStatus(record,-1)">{{ record.status_["-1"] }}</a-tag>
					</template>
					<template v-else-if="column.key === 'status0'">
						<a-tag color="pink" @click="clickStatus(record,0)">{{ record.status_["0"] }}</a-tag>
					</template>
					<template v-else-if="column.key === 'status1'">
						<a-tag color="pink" @click="clickStatus(record,1)">{{ record.status_["1"] }}</a-tag>
					</template>
					<template v-else-if="column.key === 'status2'">
						<a-tag color="pink" @click="clickStatus(record,2)">{{ record.status_["2"] }}</a-tag>
					</template>
					<template v-else-if="column.key === 'operation'"></template>
				</template>
			</a-table>

			<a-modal v-model:visible="visible" :width="400" :title="`${formState.key ? '修改' : '添加'}审批流`" @ok="saveIndustry">
				<a-form ref="formRef" :model="formState" v-bind="{labelCol: { style: { width: '100px' } }}">
					<a-form-item label="名称" name="name" :rules="{required:true, message:'请输入名称'}">
						<a-input v-model:value="formState.name" />
					</a-form-item>
					<a-form-item label="审批角色" name="role_ids">
						<a-tree-select v-model:value="formState.role_ids" :show-search="true" :tree-checkable="false" multiple :dropdown-style="{}" tree-default-expand-all :tree-data="roleSource" :field-names="{children: 'children',label: 'label',value: 'id'}" tree-node-filter-prop="label"></a-tree-select>
					</a-form-item>
					<!-- 					<a-form-item label="审批人角色" name="approver_role">
						<a-input v-model:value="formState.approver_role" />
					</a-form-item>-->
					<a-form-item label="模块ID" name="module_id">
						<a-input v-model:value="formState.module_id" />
					</a-form-item>
					<a-form-item label="路由地址" name="route_path">
						<a-input v-model:value="formState.route_path" />
					</a-form-item>
					<a-form-item label="路由名称" name="route_name">
						<a-input v-model:value="formState.route_name" />
					</a-form-item>
					<!-- <a-form-item label="ID" name="id">
						<a-input v-model:value="formState.id" />
					</a-form-item>-->
					<a-form-item label="备注" name="remark">
						<a-input v-model:value="formState.remark" />
					</a-form-item>
				</a-form>
			</a-modal>
		</div>
	</div>
</template>
<script setup>
import { ref, reactive, computed, getCurrentInstance, watch } from "vue";
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined } from "@ant-design/icons-vue";
import router from "../router";
const { proxy } = getCurrentInstance();

import { post, treeToList } from "../utils";
import { usePagination } from "vue-request";
const roleSource = ref();
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const query = route.query;
post("company/tree").then(data => {
	roleSource.value = data.map(d => {
		//判断是否为公司
		if (d.value.slice(-2) === "-0") {
			//d.disabled = true;
			//d.disableCheckbox = true;

			//分公司不可选
			d.selectable = false;
		}
		return d;
	});
});
const searchRef = ref();
const searchState = reactive({});

const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 250
}));

const columns = [
	{
		title: "ID",
		dataIndex: "id",
		key: "id",
		width: 80,
		align: "left",
		fixed: "left"
	},
	// {
	// 	title: "模块ID",
	// 	dataIndex: "module_id",
	// 	key: "module_id",
	// 	width: 120,
	// 	align: "left",
	// },
	{
		title: "退回",
		key: "status-1",
		width: 100
	},
	{
		title: "待审核",
		key: "status0",
		width: 100
	},
	{
		title: "审核中",
		key: "status1",
		width: 100
	},
	{
		title: "已完成",
		key: "status2",
		width: 100
	},
	// {
	// 	title: "路由名称",
	// 	dataIndex: "route_name",
	// 	key: "route_name",
	// 	width: 120,
	// },
	// {
	// 	title: "路由地址",
	// 	dataIndex: "route_path",
	// 	key: "route_path",
	// 	width: 120,
	// },
	{
		title: "名称",
		dataIndex: "name",
		sorter: false,
		width: 200,
		ellipsis: true
	},

	{
		title: "审批节点",
		key: "flowTypeNodes",
		sorter: false,
		width: 300,
		resizable: true
		// ellipsis: true
	},
	{
		title: "备注",
		dataIndex: "remark",
		sorter: false,
		width: 360,
		ellipsis: true
	},
	//自动调节表格剩余宽度
	{}
	// {
	// 	title: "操作",
	// 	key: "operation",
	// 	sorter: false,
	// 	fixed: "right",
	// 	width: 240,
	// 	align: "center",
	// },
];

const { data, loading, run, current, pageSize, total } = usePagination(params => post("flow/getFlowTypeIndex", { ...params, ...searchState }), {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});
const flowSource = computed(() => data.value?.data || []);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.name) searchState.name = query.name;
	// router.replace({ query: {}})
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

watch(flowSource, value => {
	const { name } = searchState;
	if (name) expandedRowKeys.value = treeToList(JSON.parse(JSON.stringify(value))).map(d => d.id);

	//删除记录后返回上一页
	if (value.length === 0 && current.value > 1) current.value--;
});

const expandedRowKeys = ref([]);
const expandedRowsChange = e => {
	expandedRowKeys.value = e;
};

const rowSelection = ref();

const visible = ref(false);

const formRef = ref();
const formState = ref({});

const toDetail = row => {
	// router.push({ name: "flowDetail", params: { id: rowid } });
	router.push({
		name: "flow",
		params: { type_id: row.id }
	});
	// formState.value = {
	// 	parent_id: parseInt(parentId) || 0
	// };
	// visible.value = true;
};
const addIndustry = parentId => {
	formRef.value?.clearValidate();
	formState.value = {
		role_ids: []
	};
	visible.value = true;
};
const editIndustry = record => {
	formRef.value?.clearValidate();

	visible.value = true;
	const data = { ...record };
	data.role_ids = record.roles.map(d => d.id);
	// formState.value = { ...record };
	formState.value = data;
};
const saveIndustry = () => {
	formRef.value
		.validate()
		.then(() => {
			proxy.$message.destroy();
			const params = { ...formState.value };
			if (params.birthday) params.birthday = params.birthday.format("YYYY-MM-DD");
			params.role_ids = params.role_ids.join(",");

			post("flow/saveFlowType", params)
				.then(() => {
					proxy.$message.success("提交成功", 1);
					visible.value = false;

					// expandedRowKeys.value.push(params.parent_id);

					initData();
				})
				.catch(err => {
					proxy.$message.error(err);
				});
		})
		.catch(err => {});
};
const clickStatus = (row, status) => {
	//console.log(row, status);
	if (row.route_name) {
		router.push({
			name: row.route_name,
			query: { flow_module_id: row.module_id, flow_status: status }
		});
	} else if (row.route_path) {
		router.push({
			path: row.route_path,
			query: { flow_module_id: row.module_id, flow_status: status }
		});
	}
};
const deleteIndustry = id => {
	proxy.$confirm({
		title: "确认提示",
		content: `确定要删除${typeof id === "number" ? "当前" : "选中"}的行业吗？`,
		okText: "确认",
		cancelText: "取消",
		onOk() {
			post("flow/deleteFlowType", { id }).then(() => {
				proxy.$message.success("行业删除成功");

				initData();
			});
		}
	});
};

watch(visible, value => {
	if (value) formRef.value?.clearValidate();
});
</script>

<style scoped>
.toolbar {
	padding: 12px;
	background: #fff;
}

.container {
	background: #fff;
	padding: 12px;
}
</style>